package org.jvm.instruction.control;

import org.jvm.instruction.base.*;
import org.jvm.rtda.thread.Frame;

/**
 * @author 海燕
 * @date 2023/1/29
 */
public class LOOKUP_SWITCH implements Instruction {

    private int defaultOffset;
    private int npairs;
    private int[] matchOffsets;

    @Override
    public void fetchOperands(ByteCodeReader reader) {
        reader.skipPadding();
        this.defaultOffset = reader.readUint32();
        this.npairs = reader.readUint32();
        this.matchOffsets = reader.readUint32s(this.npairs * 2);
    }

    @Override
    public void execute(Frame frame) {
        int key = frame.getOperandStack().popInt();
        for (int i = 0; i < this.npairs * 2; i += 2) {
            if (this.matchOffsets[i] == key) {
                int offset = this.matchOffsets[i + 1];
                InstructionUtil.branch(frame, offset);
                return;
            }
        }
        InstructionUtil.branch(frame, this.defaultOffset);
    }
}
